package cn.wjh.business.config;

import cn.wjh.common.core.domain.BaseEntity;
import cn.wjh.common.core.text.Convert;
import cn.wjh.common.utils.ServletUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static cn.wjh.common.core.page.TableSupport.*;

@Configuration
public class CacheConfig {
    /**
     * 生成缓存的key值
     */
    @Bean("cacheKeyGenerator")
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            List<Object> list = Arrays.asList(params);
            Integer pageNum = Convert.toInt(ServletUtils.getParameter(PAGE_NUM), 1);
            Integer pageSize = Convert.toInt(ServletUtils.getParameter(PAGE_SIZE), 10);
            String key = target.getClass().getName() + ":" + method.getName() + list + "_" + pageNum + "_" + pageSize;
            try {
                if (list.isEmpty() || !(list.get(0) instanceof BaseEntity)) {
                    return key;
                }
                // 反射
                Field field = BaseEntity.class.getDeclaredField("params");
//                Field field = list.get(0).getClass().getField("params");
                field.setAccessible(true);
                Map<String, Object> _params = (Map<String, Object>) field.get(list.get(0));
                return key + "_" + _params;
            } catch (NoSuchFieldException | IllegalAccessException e) {
//                e.printStackTrace();
//                return key;
                throw new RuntimeException(e);
            }
        };
    }
}
